package com.yuanwushe.blue.onceandroid;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yuanwushe.blue.models.App;

import java.io.IOException;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http);
        Button button = findViewById(R.id.http_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            OkHttpClient client = new OkHttpClient();
                            RequestBody requestBody = new FormBody.Builder()
                                    .add("username", "admin")
                                    .add("password", "123456")
                                    .build();
                            Request request = new Request.Builder()
                                    .url("http://192.168.1.106/data.json")
                                    .post(requestBody)
                                    .build();
                            Response response = client.newCall(request).execute();
                            String data = response.body().string();
                            showResponse(data);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    private void showResponse(final String data) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Gson gson = new Gson();
                List<App> apps = gson.fromJson(data, new TypeToken<List<App>>(){}.getType());
                String s = "";
                for (App app : apps) {
                    s += "id:"+String.valueOf(app.getId())+",name:" + app.getName() + ",version:" + String.valueOf(app.getVersion());
                }
                TextView textView = findViewById(R.id.text);
                textView.setText(s);
            }
        });
    }
}
